package com.y5neko.RadiantKnightExploit.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Objects;

public class FirstInit {
    /**
     * 释放resource文件到文件系统
     * @param sourceFile resource文件相对路径
     * @param targetFile 释放文件路径
     */
    public static void releaseResource(String sourceFile, String targetFile){
        Path checkFilePath = Paths.get(targetFile);
        Path checkPath = checkFilePath.getParent();

        if (!Files.exists(checkPath)) {
            try {
                // 如果路径不存在，则创建它（包括所有必要的父目录）
                Files.createDirectories(checkPath);
                System.out.println("Directory created successfully: " + checkPath);
            } catch (IOException e) {
                System.err.println("Failed to create directory: " + checkPath);
            }
        } else {
            System.out.println("Directory already exists: " + checkPath);
        }

        if (!Files.exists(checkFilePath)) {
            try (InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(sourceFile);
                 FileOutputStream outputStream = new FileOutputStream(targetFile)) {
                byte[] buffer = new byte[1024];
                int length;
                while ((length = Objects.requireNonNull(inputStream).read(buffer)) > 0) {
                    outputStream.write(buffer, 0, length);
                }
                System.out.println("File copied successfully.");
            } catch (IOException e) {
                System.err.println(e.getMessage());
            }
        } else {
            System.out.println("File already exists: " + checkPath);
        }
    }

    /**
     * 初始化引导,释放静态文件
     */
    public static void firstInit() {
        // 初始化文件列表
        String[] resourceFiles = new String[]{
                "config/proxy_config.json"
        };

        for (String resourceFile : resourceFiles) {
            releaseResource(resourceFile, System.getProperty("user.dir") + File.separator + resourceFile);
        }
    }
}
